package com.nku.mason.lucene.secondapp;

import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;

import com.nku.mason.lucene.entity.Article;
import com.nku.mason.lucene.util.LuceneUtil;

/**
 * 重构第一个应用,应用LuceneUtil
 * 
 * @author Mason
 *
 */
public class SecondApp {

	public static void createIndexDB() {
		
		Article article = new Article(1, "南开", "南开大学排名每况愈下");

		Document document = LuceneUtil.javabean2Document(article);
		try {
			IndexWriter indexWriter = new IndexWriter(LuceneUtil.getDirectory(), LuceneUtil.getAnalyzer(), MaxFieldLength.LIMITED);
			indexWriter.addDocument(document);
			System.out.println("new document added...");
			indexWriter.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void searchForKeyWord(String keyword,int maxResultNum) {
		
		List<Article> res = new ArrayList<>();
		try{
			IndexSearcher indexSearcher = new IndexSearcher(LuceneUtil.getDirectory());
			QueryParser queryParser = new QueryParser(LuceneUtil.getVersion(), "content", LuceneUtil.getAnalyzer());
			Query query = queryParser.parse(keyword);
			TopDocs topDocs = indexSearcher.search(query, maxResultNum);
			ScoreDoc[] scoreDocs = topDocs.scoreDocs;
			for(ScoreDoc scoreDoc : scoreDocs){
				
				Document document = indexSearcher.doc(scoreDoc.doc);
				System.out.println(document.get("id"));
				Article article = (Article) LuceneUtil.document2JavaBean(document, Article.class);
				
				res.add(article);
			}
			
			for(Article article : res){
				System.out.println(article);
			}
			indexSearcher.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		//createIndexDB();
		searchForKeyWord("工", 100);
	}
}
